1831B - Array merging - CodeForces Solution


constructive algorithms greedy

Please click on ads to support us..

Python Code:

import sys,math,cmath,time
from bisect import bisect_left
start_time = time.time()


def solve():
    n=inp()
    a=[int(k) for k in inps()]
    b=[int(k) for k in inps()]
    a.append(-1)
    b.append(-1)
        
    d1={}
    d2={}
    c=1
    c1=1
    for i in range(n):
        d1[a[i]]=d1.get(a[i],0)
        d2[b[i]]=d2.get(b[i],0)
    for i in range(n):
        if(a[i]==a[i+1]):
            c+=1
        else:
            d1[a[i]]=max(d1[a[i]],c)
            c=1
        if(b[i]==b[i+1]):
            c1+=1
        else:
            d2[b[i]]=max(d2[b[i]],c1)
            c1=1
    ans=0
    for i in d1:
        ans=max(ans,d1[i]+d2.get(i,0))
    for i in d2:
        ans=max(ans,d2[i]+d1.get(i,0))
    print(ans)









def main():

    testcases = 1
    testcases = inp()
    for each_testcase in range(testcases):
        solve()
            
def inp():
    return(int(input()))
def inps():
    return(input().split())

ONLINE_JUDGE = __debug__ if ONLINE_JUDGE:
    input = sys.stdin.readline

main()

C++ Code:

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;


int main()
{
    cin.tie(0);cout.tie(0);ios::sync_with_stdio(0);
    int t;
    cin >> t;
    while (t--){
        int n;
        cin >> n;
        int a[n], b[n];
        for(int i = 0; i < n; i++) cin >> a[i];
        for(int i = 0; i < n; i++) cin >> b[i];
        int c[2 * n + 10] = {0};
        int cur = 0;
        int k = -1;
        int ans = 0;
        for(int i = 0; i < n; i++){
            if(a[i] != k){
                k = a[i];
                cur = 0;
            }
            cur++;
            c[k] = max(cur, c[k]);
            ans = max(ans, c[k]);
        }   
        cur = 0, k = -1;     
        for(int i = 0; i < n; i++){
            if(b[i] != k){
                k = b[i];
                cur = 0;
            }
            cur++;
            ans = max(ans, cur + c[k]);
        }
        cout << ans << '\n';
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

415. Add Strings
22. Generate Parentheses
13. Roman to Integer
2. Add Two Numbers
515. Find Largest Value in Each Tree Row
345. Reverse Vowels of a String
628. Maximum Product of Three Numbers
1526A - Mean Inequality
1526B - I Hate 1111
1881. Maximum Value after Insertion
237. Delete Node in a Linked List
27. Remove Element
39. Combination Sum
378. Kth Smallest Element in a Sorted Matrix
162. Find Peak Element
1529A - Eshag Loves Big Arrays
19. Remove Nth Node From End of List
925. Long Pressed Name
1051. Height Checker
695. Max Area of Island
402. Remove K Digits
97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function